package com.ddstation.clinic_info.controller;

import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.imageio.ImageIO;
import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ddstation.clinic_info.model.ClinicInfoModel;
import com.ddstation.common.entity.DdPictureEntity;
import com.ddstation.common.mapper.DdPictureMapper;
import com.ddstation.common.property.SystemProperties;
import com.ddstation.common.service.DataDictionaryService;
import com.ddstation.common.service.ImageService;
import com.ddstation.common.util.AliCloudOssUtil;
import com.ddstation.crm.institution.mapper.DtHealthManageInstitutionMapper;
import com.ddstation.doctor.mapper.DdDoctorMapper;
import com.ddstation.exam.entity.DtHealthManageInstitutionGroupEntity;
import com.ddstation.exchange.service.DtHealthManageInstitutionGroupService;
import com.ddstation.master.entity.MaDataDictionaryEntity;
import com.ddstation.statement.model.IllegalInstitutionModel;
import com.ddstation.statement.service.StatisticsStatementService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ddstation.clinic_info.service.ClinicInfoService;
import com.ddstation.common.model.ImageModel;
import com.ddstation.crm.institution.entity.DtHealthManageInstitutionEntity;
import com.ddstation.crm.login.bean.SessionLoginData;
import com.ddstation.doctor.entity.DdDoctorEntity;
import com.ddstation.doctor_verify.service.DoctorVerifyService;
import com.ddstation.sewage.service.SewageService;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

@Controller
public class ClinicInfoController {

	/**
	 * 机构信息页面 跳转
	 *
	 * @param
	 *
	 * @return
	 */
	@RequestMapping(value="invs_clinic_info.do")
	public String summarizeInitEvent(
			Model model,
			HttpSession session) {

		SessionLoginData loginData = (SessionLoginData) session.getAttribute(SessionLoginData.KEY);

		//二级联动医疗机构类别
		List<MaDataDictionaryEntity> typeFirstList = dataDictionaryService.getCodeList("institution_type_first");
		List<MaDataDictionaryEntity> typeSecondList = dataDictionaryService.getCodeList("institution_type_second");

		model.addAttribute("typeFirstList", typeFirstList);
		model.addAttribute("typeSecondList", typeSecondList);

		//乡镇/街道
		List<IllegalInstitutionModel> townList = statisticsStatementService.searchIllegalInstitution(loginData.getInstitution().getId());
		model.addAttribute("townList", townList);


		return "pc/clinic_info/clinic_info";
	}

	/**
	 * 机构信息页面数据查询 接口
	 *
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value="invs_clinic_info.do/load", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> loadClinicListEvent(
			@RequestParam (required=false)String institutionId,
			@RequestParam (required=false)String institutionName,
			@RequestParam Integer underInvs,
			@RequestParam Integer prescriptionInvs,
			@RequestParam Integer occupationalLicenceStatus,
			@RequestParam String institutionTypeFirst,
			HttpSession session) throws ParseException {

		Map<String, Object> ret = new HashMap();
		ret.put("errcode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");

		SessionLoginData loginData = (SessionLoginData) session.getAttribute(SessionLoginData.KEY);
		// 查询实施
		List<ClinicInfoModel> clinicInfoModelList = clinicInfoService.searchInstitutions(loginData.getInstitution().getId(), institutionId, institutionName, underInvs,prescriptionInvs,institutionTypeFirst);
		List<ClinicInfoModel> clinicInfoModelList2=new ArrayList<>();
		List<ClinicInfoModel> clinicInfoModelList3=new ArrayList<>();
		List<ClinicInfoModel> clinicInfoModelList4=new ArrayList<>();
		for (ClinicInfoModel clinicInfoModel : clinicInfoModelList) {
			//判断图片是否存在【营业执照等】
			if ("1".equals(clinicInfoModel.getBusinessLicence())) {
				clinicInfoModel.setBusinessLicence(null);
			}
			if ("1".equals(clinicInfoModel.getOccupationalLicence())) {
				clinicInfoModel.setOccupationalLicence(null);
			}
			//执业范围
			String technicalOffices = clinicInfoModel.getTechnicalOffices();
			if(technicalOffices!=null&&technicalOffices!="") {
				List<String> technicalOfficesArray = Arrays.asList(technicalOffices.split(","));
				List<MaDataDictionaryEntity> maDataDictionaryEntityList = dataDictionaryService.getMaDataDictoryByEntity("technical_offices", technicalOfficesArray);
				StringBuffer technicalOfficesBuffer = new StringBuffer();
				if (maDataDictionaryEntityList.size() > 0) {
					maDataDictionaryEntityList.forEach(p -> {
						technicalOfficesBuffer.append(p.getFullName());
						technicalOfficesBuffer.append(",");
					});
				}
				String technicalOfficesNames=technicalOfficesBuffer.toString();
				technicalOfficesNames=technicalOfficesNames.substring(0,technicalOfficesNames.lastIndexOf(","));
				clinicInfoModel.setTechnicalOfficesNames(technicalOfficesNames);
			}
			SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			Calendar cale=Calendar.getInstance();
			String time = format.format(cale.getTime());
			Date today = format.parse(time);

			if(occupationalLicenceStatus!=9){
				if(clinicInfoModel.getOccupationalLicenceEndDate()==null){
					if(occupationalLicenceStatus==2){
						clinicInfoModelList4.add(clinicInfoModel);
					}
				}else {
					if(occupationalLicenceStatus==0 &&clinicInfoModel.getOccupationalLicenceEndDate().getTime()<today.getTime()){
						clinicInfoModelList2.add(clinicInfoModel);
					}else if(occupationalLicenceStatus==1 &&clinicInfoModel.getOccupationalLicenceEndDate().getTime()>=today.getTime()){
						clinicInfoModelList3.add(clinicInfoModel);
					}
				}
			}

		}

		if (occupationalLicenceStatus==9){
			ret.put("datalist", clinicInfoModelList);
		}else if (occupationalLicenceStatus==0){
			ret.put("datalist", clinicInfoModelList2);
		}else if(occupationalLicenceStatus==1) {
			ret.put("datalist", clinicInfoModelList3);
		}else {
			ret.put("datalist", clinicInfoModelList4);
		}
//		ret.put("datalist", clinicInfoModelList);
		ret.put("errcode", 0);
		ret.put("errMsg", "");
		return ret;
	}

	/**
	 * 卫监上报项目实施规则自助设置历史查询
	 *
	 * @return
	 */
	@RequestMapping(value="invs_clinic_info.do/load_invs_set_his", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> loadClinicInvsSetHisListEvent(
			@RequestParam String institutionId,
			HttpSession session)  {

		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errcode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");

		SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY );

		// 访问权限check(防止异常调用)
		if ( !sewageService.checkAccessAuthority(loginData.getInstitution().getId(),institutionId) ){
			ret.put("errMsg", "没有访问权限！");
			return ret;
		}

		// 查询实施
		ret.put("clinicInfoModel",clinicInfoService.searchInvsSettingsInfo(institutionId));

		ret.put("errcode", 0);
		ret.put("errMsg", "");
		return ret;
	}

	/**
	 * 查询营业执照 接口
	 *
	 * @return
	 */
	@RequestMapping(value="invs_clinic_info.do/load_license_image", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> loadWasteDeliveryDetailEvent(
			@RequestParam String institutionId,
			@RequestParam String type,
			HttpSession session) {

		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errcode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");

		SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY );
		if ( !sewageService.checkAccessAuthority(loginData.getInstitution().getId(),institutionId) ){
			ret.put("errMsg", "没有访问权限！");
			return ret;
		}

		// 参数确认
		if ( !"business_licence".equals(type) && !"occupational_licence".equals(type) ){
			ret.put("errMsg", "type参数错误！");
			return ret;
		}

		// 查询实施
		ret.put("imagelist",clinicInfoService.fetchImage(institutionId, type));

		ret.put("errcode", 0);
		ret.put("errMsg", "");

		return ret;
	}


	/**
	 * 查询营业执照 接口
	 *
	 * @return
	 */
	@RequestMapping(value="invs_clinic_info.do/update_license_image", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> updateWasteDeliveryDetailEvent(
			@RequestParam String institutionId,
			@RequestParam String type,
			@RequestParam String base64,
			HttpSession session) {
		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errcode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");
		SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY );
		if ( !sewageService.checkAccessAuthority(loginData.getInstitution().getId(),institutionId) ){
			ret.put("errMsg", "没有访问权限！");
			return ret;
		}

		//修改参数
		DtHealthManageInstitutionEntity entity = new DtHealthManageInstitutionEntity();
		entity.setId(institutionId);
		if("business_licence".equals(type)){
            if("yes".equals(SystemProperties.IS_INNER_DATA)){
                //内网直接插入base64
                entity.setBusinessLicence(base64);
            }else{
                //外网处理base64图片至OSS得到url
                String ossUrl = AliCloudOssUtil.getUrlByBase64(null,base64);
                entity.setBusinessLicence(ossUrl);
            }
		}else if("occupational_licence".equals(type)){
            if("yes".equals(SystemProperties.IS_INNER_DATA)){
                //内网直接插入base64
                entity.setOccupationalLicence(base64);
            }else{
                //外网处理base64图片至OSS得到url
                String ossUrl = AliCloudOssUtil.getUrlByBase64(null,base64);
                entity.setOccupationalLicence(ossUrl);
            }
		}else{
			ret.put("errMsg", "type参数错误！");
			return ret;
		}

		// 修改
		clinicInfoService.updateClinicInfo(entity);

		ret.put("errcode", 0);
		ret.put("errMsg", "");

		return ret;
	}


	/**
	 * 查询营业执照 接口
	 *
	 * @return
	 */
	@RequestMapping(value="invs_clinic_info.do/update_license_image_picId", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> updateWasteDeliveryDetailPicIdEvent(
			@RequestParam Integer picId,
			@RequestParam String type,
			@RequestParam String base64,
			HttpSession session) {
		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errcode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");

		//判断参数
		if(!"id_card".equals(type) && !"qualification".equals(type) && !"doctor_licence".equals(type)){
			ret.put("errMsg", "type参数错误！");
			return ret;
		}

		if("yes".equals(SystemProperties.IS_INNER_DATA)){
			//内网直接插入base64
			ddPictureMapper.updateByPicId(base64,picId);
		}else{
			//外网处理base64图片至OSS得到url
			String ossUrl = AliCloudOssUtil.getUrlByBase64(null,base64);
			ddPictureMapper.updateByPicId(ossUrl,picId);
		}

		ret.put("errcode", 0);
		ret.put("errMsg", "");

		return ret;
	}

	@RequestMapping(value="invs_clinic_info.do/delete_license_image_picId", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> deleteWasteDeliveryDetailPicIdEvent(
			@RequestParam String doctorId,
			@RequestParam String type,
			@RequestParam Integer picId,
			@RequestParam String institutionId,
			HttpSession session) {
		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errcode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");

		SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY );
		// 访问权限check(防止异常调用)
		if ( !sewageService.checkAccessAuthority(loginData.getInstitution().getId(),institutionId) ){
			ret.put("errMsg", "对诊医疗机构没有访问权限！");
			return ret;
		}

		//判断类型
		if ( !"id_card".equals(type) &&
				!"qualification".equals(type) &&
				!"doctor_licence".equals(type) ){
			ret.put("errMsg", "参数错误！");
			return ret;
		}

		//查询医生数据是否存在
		DdDoctorEntity ddDoctorEntity = ddDoctorMapper.selectDoctorInfoByKey(doctorId, institutionId);
		if(ddDoctorEntity == null){
			ret.put("errMsg", "数据不存在！");
			return ret;
		}

		//删除图片
		int count = ddPictureMapper.deleteById(picId);
		if(count < 1){
			ret.put("errMsg", "图片删除失败！");
			return ret;
		}

		DdDoctorEntity newDoctorEntity = new DdDoctorEntity();
		newDoctorEntity.setId(ddDoctorEntity.getId());
		newDoctorEntity.setInstitutionId(ddDoctorEntity.getInstitutionId());
		//根据类型更新医生数据
		switch (type){
			case "id_card":
				newDoctorEntity.setIdCardAtta(outPicIds(ddDoctorEntity.getIdCardAtta(),""+picId));
				break;
			case "qualification":
				newDoctorEntity.setQualificationAtta(outPicIds(ddDoctorEntity.getQualificationAtta(),""+picId));
				break;
			case "doctor_licence":
				newDoctorEntity.setDoctorLicenceAtta(outPicIds(ddDoctorEntity.getDoctorLicenceAtta(),""+picId));
				break;
		}

		//修改数据
		ddDoctorMapper.update(newDoctorEntity);

		ret.put("errcode", 0);
		ret.put("errMsg", "");

		return ret;
	}

	/**
	 * 下载营业执照图片
	 *
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value="invs_clinic_info.do/download", method = RequestMethod.POST)
	public void downloadImageEvent(
			@RequestParam String institutionId,
			@RequestParam String institutionName,
			@RequestParam String type,
			HttpServletResponse response,
			HttpSession session) {

		SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY );
		if ( !sewageService.checkAccessAuthority(loginData.getInstitution().getId(),institutionId) ){
			return;
		}

		// 参数确认
		if ( !"business_licence".equals(type) && !"occupational_licence".equals(type) ){
			return;
		}
		String destFileName = "";
		if ( "business_licence".equals(type) ){
			destFileName = "营业执照-" + institutionName ;
		} else {
			destFileName = "医师执业许可证-" + institutionName;
		}
		// 查询实施
		List<ImageModel> urlList = clinicInfoService.fetchImage(institutionId, type);
		if(urlList.size() == 0){
			throw new RuntimeException("图片尚未传输完成");
		}

		try {

			for (ImageModel oneFile : urlList){
				BufferedOutputStream output=null;
				BufferedInputStream input=null;
				try {
					output=new BufferedOutputStream(response.getOutputStream());
					//中文文件名必须转码为ISO8859-1,否则为乱码 2
					String fileNameDown=new String(destFileName.getBytes(),"ISO8859-1");
					int idx =oneFile.getObjKey().lastIndexOf(".");
					if ( idx > 0 ){
						fileNameDown = fileNameDown + oneFile.getObjKey().substring(idx);
					} else {
						fileNameDown = fileNameDown + ".jpg";
					}
					response.setContentType("application/octet-stream;charset=ISO8859-1");
					response.setHeader("Content-Disposition","attachment;filename="+fileNameDown);
					response.setHeader("Set-Cookie", "fileDownload=true; path=/"); // jQuery.fileDownload.js 文件下 成功响应
					if("yes".equals(SystemProperties.IS_INNER_DATA)){
						//内网下载
						String base64String = oneFile.getOriginImgUrl();
						if(StringUtils.isNotBlank(base64String)){
							base64String = base64String.substring(22,base64String.length());
						}
						byte[] bs = decoder.decodeBuffer(base64String);
						output.write(bs);
						response.flushBuffer();
					}else{
						//外网下载
						URL url=new URL(oneFile.getOriginImgUrl());
						HttpURLConnection conn=(HttpURLConnection)url.openConnection();
						//设置超时间为3秒
						conn.setConnectTimeout(3*1000);
						//防止屏蔽程序抓取而返回403错误
						conn.setRequestProperty("User-Agent","Mozilla/4.0(compatible;MSIE5.0;WindowsNT;DigExt)");
						//得到输入流
						InputStream inputStream=conn.getInputStream();
						//获取自己数组
						byte[] bs = readInputStream(inputStream);
						output.write(bs);
						response.flushBuffer();
					}
				} catch(Exception e){
					throw new RuntimeException("营业执照/医师执业许可证下载出错。institutionId:"+institutionId+","+e.getMessage());
					//用户可能取消了下载
				} finally {
					if(input!=null){
						try{
							input.close();
						}catch(IOException e){
							e.printStackTrace();
						}
						if(output!=null)
							try{
								output.close();
							}catch(IOException e){
								e.printStackTrace();
							}
					}
				}
//	    		URL url=new URL(oneFile.getOriginImgUrl());
//				HttpURLConnection conn=(HttpURLConnection)url.openConnection();
//				//设置超时间为3秒
//		    	conn.setConnectTimeout(3*1000);
//		    	//防止屏蔽程序抓取而返回403错误
//		    	conn.setRequestProperty("User-Agent","Mozilla/4.0(compatible;MSIE5.0;WindowsNT;DigExt)");
//		    	//得到输入流
//		    	InputStream inputStream=conn.getInputStream();
//		    	//获取自己数组
//		    	byte[]bs=readInputStream(inputStream);
//		    	response.setContentType("application/octet-stream;charset=ISO8859-1");
//		    	BufferedOutputStream output=null;
//		    	BufferedInputStream input=null;
//		    	try{
//			    	output=new BufferedOutputStream(response.getOutputStream());
//			    	//中文文件名必须转码为ISO8859-1,否则为乱码
//			    	String fileNameDown=new String(destFileName.getBytes(),"ISO8859-1");
//			    	int idx =oneFile.getObjKey().lastIndexOf(".");
//			    	if ( idx > 0 ){
//			    		fileNameDown = fileNameDown + oneFile.getObjKey().substring(idx);
//			    	} else {
//			    		fileNameDown = fileNameDown + ".jpg";
//			    	}
//			    	//作为附件下载
//			    	response.setHeader("Content-Disposition","attachment;filename="+fileNameDown);
//			    	response.setHeader("Set-Cookie", "fileDownload=true; path=/"); // jQuery.fileDownload.js 文件下 成功响应
//			    	output.write(bs);
//			    	response.flushBuffer();
//		    	}catch(Exception e){
////				    log.error("Downloadlogfileerror",e);
//		    		throw new RuntimeException("营业执照/医师执业许可证下载出错。institutionId:"+institutionId+","+e.getMessage());
//			    	//用户可能取消了下载
//			    } finally {
//			    	if(input!=null){
//				    	try{
//				    		input.close();
//				    	}catch(IOException e){
//				    		e.printStackTrace();
//				    	}
//				    	if(output!=null)
//				    	try{
//				    		output.close();
//				    	}catch(IOException e){
//				    		e.printStackTrace();
//				    	}
//				    }
//				 }
			}
		}catch(Exception e){
			throw new RuntimeException("营业执照/医师执业许可证下载出错。institutionId:"+institutionId+","+e.getMessage());
		}
	}

	static BASE64Decoder decoder = new sun.misc.BASE64Decoder();

	/**
	   * 从输入流中获取字节数组
	   * @param inputStream
	   * @return
	   * @throws IOException
	   */
	public static byte[] readInputStream(InputStream inputStream) throws IOException {
		byte[] buffer = new byte[1024];
		int len = 0;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		while((len = inputStream.read(buffer)) != -1) {
			bos.write(buffer, 0, len);
		}
		bos.close();
		return bos.toByteArray();
	}

	/**
	 * 查看医生图片
	 *
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value="invs_clinic_info.do/load_image", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> loadDoctorVerifyImageListEvent(
			@RequestParam String institutionId,
			@RequestParam Integer doctorId,
			@RequestParam String type,//查看文件的类型
			HttpSession session) {

		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errcode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");

		SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY );
		// 访问权限check(防止异常调用)
		if ( !sewageService.checkAccessAuthority(loginData.getInstitution().getId(),institutionId) ){
			ret.put("errMsg", "对诊医疗机构没有访问权限！");
			return ret;
		}

		// 身份证  //医生资格证书 qualification //医生执业证书 doctor_licence
		if ( !"id_card".equals(type) &&
				!"qualification".equals(type) &&
				!"doctor_licence".equals(type) ){
			ret.put("errMsg", "参数错误！");
			return ret;
		}

		// 是否是演示的卫监机构
		Integer isTest = loginData.getInstitution().getIsTest();
		ret.put("imagelist", doctorVerifyService.searchImage(isTest, doctorId, institutionId, type));

		// 查询

		ret.put("errcode", 0);
		ret.put("errMsg", "");
		return ret;
	}


	/**
	 * 查看医生图片
	 *
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value="invs_clinic_info.do/load_image_picId", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> loadDoctorVerifyImagePicIdEvent(
			@RequestParam String institutionId,
			@RequestParam Integer doctorId,
			@RequestParam String type,//查看文件的类型
			@RequestParam String picId,//图片ID
			HttpSession session) {

		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errcode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");

		SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY );
		// 访问权限check(防止异常调用)
		if ( !sewageService.checkAccessAuthority(loginData.getInstitution().getId(),institutionId) ){
			ret.put("errMsg", "对诊医疗机构没有访问权限！");
			return ret;
		}

		// 身份证  //医生资格证书 qualification //医生执业证书 doctor_licence
		if ( !"id_card".equals(type) &&
				!"qualification".equals(type) &&
				!"doctor_licence".equals(type) ){
			ret.put("errMsg", "参数错误！");
			return ret;
		}

		ret.put("imagelist", imageService.fetchImage(picId));

		ret.put("errcode", 0);
		ret.put("errMsg", "");
		return ret;
	}



	/**
	 * 保存医生信息
	 *
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value="invs_clinic_info.do/save_doctor", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> saveDoctorInfoEvent(
			@RequestBody DdDoctorEntity doctor,
			HttpSession session) {

		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errcode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");

//        SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY );
//        // 访问权限check(防止异常调用)
// 		if ( !sewageService.checkAccessAuthority(loginData.getInstitution().getId(),institutionId) ){
// 			ret.put("errMsg", "对诊诊所没有访问权限！");
// 			return ret;
// 		}
		String INVS_URL = SystemProperties.INVS_URL;
		String isInnerData = SystemProperties.IS_INNER_DATA;


		// 数据更新
		doctorVerifyService.update(doctor);

		ret.put("errcode", 0);
		ret.put("errMsg", "");
		return ret;
	}

	/**
	 * 保存医生信息
	 *
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value="invs_clinic_info.do/save_institution", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> saveInstitutionInfoEvent(
			@RequestParam String institutionId,
			@RequestParam(required=false) Integer underInvs,//开启关闭监管
			@RequestParam(required=false) Integer prescriptionInvs,//开启关闭处方监管
			HttpSession session) {

		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errcode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");

		SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY );
		// 访问权限check(防止异常调用)
		if ( !sewageService.checkAccessAuthority(loginData.getInstitution().getId(),institutionId) ){
			ret.put("errMsg", "对诊医疗机构没有访问权限！");
			return ret;
		}

		// 数据更新
		DtHealthManageInstitutionEntity a = new DtHealthManageInstitutionEntity();
		a.setId(institutionId);

		if(underInvs != null && underInvs == 0){
		    //关闭监管同时关闭处方监管
            prescriptionInvs = 0;
        }
		if(prescriptionInvs != null && prescriptionInvs == 1){
            //打开处方监管同时打开监管
            underInvs = 1;
        }
        a.setUnderInvs(underInvs);
		a.setPrescriptionInvs(prescriptionInvs);
		//修改当前机构信息
		clinicInfoService.updateClinicInfo(a);

		//查询是否存在子机构
		DtHealthManageInstitutionGroupEntity entity = new DtHealthManageInstitutionGroupEntity();
		entity.setParentInstitutionId(institutionId);
		List<DtHealthManageInstitutionGroupEntity> groupList = dtHealthManageInstitutionGroupService.select(entity);
		if(groupList != null && groupList.size() > 0){
			//存在子机构则对全部子机构修改
			for(DtHealthManageInstitutionGroupEntity group:groupList){
				a.setId(group.getChildInstitutionId());
				//修改子机构信息
				clinicInfoService.updateClinicInfo(a);
			}
		}

		ret.put("errcode", 0);
		ret.put("errMsg", "");
		return ret;
	}

    /**
     * 保存医生信息
     *
     * @return
     * @throws ParseException
     */
    @RequestMapping(value="invs_clinic_info.do/save_pic", method = RequestMethod.POST)
    public @ResponseBody Map<String, Object> savePicEvent(
            @RequestParam String institutionId,
            @RequestParam String doctorId,//医生ID
            @RequestParam String type,//图片类型
            @RequestParam String base64,//图片base64地址
            HttpSession session) {

        Map<String, Object> ret = new HashMap<String, Object>();
        ret.put("errcode", -1);
        ret.put("errMsg", "系统出错，请稍后再试！");

        SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY );
        // 访问权限check(防止异常调用)
        if ( !sewageService.checkAccessAuthority(loginData.getInstitution().getId(),institutionId) ){
            ret.put("errMsg", "对诊医疗机构没有访问权限！");
            return ret;
        }

        //判断类型
        if ( !"id_card".equals(type) &&
                !"qualification".equals(type) &&
                !"doctor_licence".equals(type) ){
            ret.put("errMsg", "参数错误！");
            return ret;
        }

        //查询医生数据是否存在
        DdDoctorEntity ddDoctorEntity = ddDoctorMapper.selectDoctorInfoByKey(doctorId, institutionId);
        if(ddDoctorEntity == null){
            ret.put("errMsg", "数据不存在！");
            return ret;
        }

        //添加图片
        DdPictureEntity pictureEntity = new DdPictureEntity();

		if("yes".equals(SystemProperties.IS_INNER_DATA)){
			//内网直接插入base64
			pictureEntity.setPath(base64);
		}else{
			//外网处理base64图片至OSS得到url
			String ossUrl = AliCloudOssUtil.getUrlByBase64(null,base64);
			pictureEntity.setPath(ossUrl);
		}

        int count = ddPictureMapper.insert(pictureEntity);
        if(count < 1){
            ret.put("errMsg", "图片添加失败！");
            return ret;
        }

        DdDoctorEntity newDoctorEntity = new DdDoctorEntity();
        newDoctorEntity.setId(ddDoctorEntity.getId());
        newDoctorEntity.setInstitutionId(ddDoctorEntity.getInstitutionId());
        //根据类型更新医生数据
        switch (type){
            case "id_card":
                newDoctorEntity.setIdCardAtta(addPicIds(ddDoctorEntity.getIdCardAtta(),pictureEntity.getId()));
                break;
            case "qualification":
                newDoctorEntity.setQualificationAtta(addPicIds(ddDoctorEntity.getQualificationAtta(),pictureEntity.getId()));
                break;
            case "doctor_licence":
                newDoctorEntity.setDoctorLicenceAtta(addPicIds(ddDoctorEntity.getDoctorLicenceAtta(),pictureEntity.getId()));
                break;
        }

        //修改数据
        ddDoctorMapper.update(newDoctorEntity);

        ret.put("errcode", 0);
        ret.put("picId", pictureEntity.getId());
        ret.put("errMsg", "");
        return ret;
    }

    String addPicIds(String picIds,int picId){
        if(picIds == null || picIds == ""){
            picIds = "";
        }else{
            picIds += ",";
        }
        return picIds + picId;
    }

	String outPicIds(String picIds,String picId){
		StringBuffer picIdSB = new StringBuffer();
		if(picIds == null || picIds == ""){
			picIds = "";
		}else{
			String[] picIdList = picIds.split(",");
			for(String id:picIdList){
				//与移除图片id不同则存入
				if(!picId.equals(id)){
					picIdSB.append(picIdSB.length()>0?(","+id):id);
				}
			}
		}
		return picIdSB.toString();
	}


	@RequestMapping(value="invs_clinic_info.do/save_institutionType")
	public @ResponseBody Map<String, Object> saveInstitutionTypeInfoEvent(
			@RequestBody DtHealthManageInstitutionEntity _a,
			HttpSession session) {

		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errcode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");

		// 数据更新
		if (0 == dtHealthManageInstitutionMapper.update(_a)) {
			ret.put("errMsg", "更新机构类型失败，请稍后再试！");
			return ret;
		}

		//查询是否存在子机构
		DtHealthManageInstitutionGroupEntity entity = new DtHealthManageInstitutionGroupEntity();
		entity.setParentInstitutionId(_a.getInstitutionId());
		List<DtHealthManageInstitutionGroupEntity> groupList = dtHealthManageInstitutionGroupService.select(entity);
		if(groupList != null && groupList.size() > 0){
			//存在子机构则对全部子机构修改
			for(DtHealthManageInstitutionGroupEntity group:groupList){
				_a.setId(group.getChildInstitutionId());
				//修改子机构信息
				clinicInfoService.updateClinicInfo(_a);
			}
		}

		ret.put("errcode", 0);
		ret.put("errMsg", "");
		return ret;
	}

	@Inject private ClinicInfoService clinicInfoService;
	@Inject private SewageService sewageService;
	@Inject private DoctorVerifyService doctorVerifyService;
	@Inject private ImageService imageService;
	@Inject private DataDictionaryService dataDictionaryService;
	@Inject private StatisticsStatementService statisticsStatementService;
	@Inject private DtHealthManageInstitutionMapper dtHealthManageInstitutionMapper;
	@Inject private DdPictureMapper ddPictureMapper;
    @Inject private DdDoctorMapper ddDoctorMapper;
	@Inject private DtHealthManageInstitutionGroupService dtHealthManageInstitutionGroupService;




}
